// stores/auth.ts
import {defineStore} from 'pinia';
import {ref} from 'vue';
import {getOpenIdApi} from '@/api/user';

export const useAuthStore = defineStore('auth', () => {
  // State (直接从持久化存储初始化)
  const wxOpenid = ref<string | null>(uni.getStorageSync('wxOpenid') || null);
  const isLoading = ref(false);

  // Actions
  const fetchWxOpenId = async (): Promise<string | undefined> => {
    if (isLoading.value || wxOpenid.value) {
      return wxOpenid.value; // 避免重复请求
    }
    try {
      isLoading.value = true;
      // 1. 环境检查 (仅微信小程序)
      const {uniPlatform} = uni.getSystemInfoSync();
      if (uniPlatform !== 'mp-weixin') {
        console.warn('非微信环境，跳过获取OpenID');
        return;
      }

      // 2. 微信登录获取code
      const {code} = await uni.login({provider: 'weixin'});
      if (!code) throw new Error('微信登录失败: 未获取到code');

      // 3. 调用后端API获取openid
      const {code: resCode, data, message} = await getOpenIdApi(code);
      if (resCode !== 'SUCCESS' || !data?.openid) {
        throw new Error(message || '获取OpenID失败');
      }

      // 4. 更新状态并持久化
      wxOpenid.value = data.openid;
      uni.setStorageSync('wxOpenid', data.openid);
      return data.openid;

    } catch (err: any) {
      console.error('获取OpenID失败:', err);
      uni.showToast({title: err.message, icon: 'none'});
    } finally {
      isLoading.value = false;
    }
  };

  // 清除OpenID (退出登录)
  const clearOpenId = () => {
    wxOpenid.value = null;
    uni.removeStorageSync('wxOpenid');
  };

  return {
    wxOpenid,      // 响应式OpenID
    isLoading,     // 加载状态
    fetchWxOpenId, // 获取OpenID方法
    clearOpenId,   // 清除OpenID方法
  };
});